package com.david.fastmsg.service.impl;

import com.david.fastmsg.Constant.Param;
import com.david.fastmsg.modal.Album;
import com.david.fastmsg.repository.AlbumRepository;
import com.david.fastmsg.service.AlbumService;
import com.david.fastmsg.utils.ResponseUtils;
import com.david.fastmsg.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author qzw
 * @date 2021/9/6
 */
@Service
public class AlbumServiceImpl implements AlbumService {

    @Autowired
    private AlbumRepository albumRepository;

    @Override
    @Transactional
    public void uploadAlbum(String userId, String userPic) {
        Album album = new Album();
        album.setUserId(userId);
        album.setUserPic(userPic);
        album.setCreateTime(new Date());
        album.setShowDate(Utils.convertDate(new Date()));
        albumRepository.save(album);
    }

    @Override
    public Map<String, Object> getAlbum(String userId) {
        Map<String, Object> result = ResponseUtils.success();
        List<Album> albumList = albumRepository.findByUserId(userId);
        if (CollectionUtils.isEmpty(albumList)) {
            return result;
        }
        Map<String, List<String>> returnAlbum = new TreeMap<>(Comparator.reverseOrder());
        List<String> userPicList;
        for (Album album :albumList) {
            userPicList = returnAlbum.get(album.getShowDate());
            if (CollectionUtils.isEmpty(userPicList)) {
                userPicList = new ArrayList<>();
            }
            userPicList.add(album.getUserPic());
            returnAlbum.put(album.getShowDate(), userPicList);
        }

        result.put(Param.ALBUM, returnAlbum);
        return result;
    }
}
